let _ = 
  Graphics.open_graph ""
  
let sizex= Graphics.size_x () and sizey = Graphics.size_y ()
let tabheight=20


let rectangle (x,y,w,h) color = 
  let realx = x and realy = sizey - y - h in
  Graphics.set_color color;
  Graphics.draw_rect realx realy (w-1) (h-1)

let frectangle (x,y,w,h) color color2 = 
  let realx = x and realy = sizey - y - h in
  Graphics.set_color color;
  Graphics.fill_rect realx realy (w-1) (h-1);
  Graphics.set_color color2;
  Graphics.draw_rect realx realy (w-1) (h-1)

let print_tabs (x,y,w,h) lz =
  let n = Zip.length lz in
    if n <> 0 then
      let r = w mod n in
      let b,a = Zip.delete lz in
      Printf.printf "%d %d\n%!" (List.length b) (List.length a);
      let next = 
        List.fold_left 
          (fun acc e -> 
             frectangle (x+acc*w/n,y,w/n, tabheight) Graphics.green Graphics.black; 
             acc+1) 
          0 b 
      in
        frectangle (x+next*w/n,y,w/n+r, tabheight) Graphics.yellow Graphics.black;
        ignore (
          List.fold_left 
            (fun acc e -> 
               frectangle (x+(acc+1)*(w/n)+r,y,w/n, tabheight) Graphics.green Graphics.black; 
               acc+1) 
            next a)
    else
      (frectangle (x,y,w, tabheight) Graphics.blue Graphics.black)

let rec print_subtree focus ((c,d),l) = 
  rectangle c Graphics.black;
  match l with
    Layout.Leaf lz -> print_tabs c lz
  | Layout.Node nz -> Zip.iter (print_subtree false) nz

let print lay =  
  let rec _print focus (l,p) =
    try
      let (l',p') = Layout._up (l,p) in
        _print false (l',p');
    with Layout.LocErr s -> ();
    print_subtree focus l
  in
  let _printfoc (((c,d),l),p) = 
    rectangle c Graphics.red
  in
    Graphics.clear_graph ();
    _print true lay;
    _printfoc lay

let _ = 
  let foc = ref (Layout.empty (0,0,sizex, sizey), Layout.Top) in
    foc := Layout.insert "hop" !foc;
  while true do
    try
    print !foc;
    let c = Graphics.read_key () in
    match c with
      'q' -> exit 0
    | 'h' -> foc := Layout._previous !foc 
    | 'j' -> foc := Layout._down !foc 
    | 'k' -> foc := Layout._up !foc 
    | 'l' -> foc := Layout._next !foc 
    | 'p' -> foc := Layout.previous !foc 
    | 'n' -> foc := Layout.next !foc 
    | 'P' -> foc := Layout.tab_previous !foc 
    | 'N' -> foc := Layout.tab_next !foc 
    | 'm' -> foc := Layout.merge !foc
    | 'i' -> foc := Layout.insert "plop" !foc
    | 's' -> foc := Layout.down (Layout.split Layout.H !foc)
    | 'v' -> foc := Layout.down (Layout.split Layout.V !foc)
(*    | 'c' -> Layout.newtab !foc
    | 'n' -> Layout.nextab !foc*)
    | _ -> ()
    with 
        Layout.LocErr s -> Printf.printf "Loc. Error : %s\n%!" s;
      | Layout.ContErr s -> Printf.printf "Context Error : %s\n%!" s;
      | Layout.TabErr s -> Printf.printf "Tab Error : %s\n%!" s;
      | Layout.SplitErr s -> Printf.printf "Split Error : %s\n%!" s;

  done
